<?php

namespace app\api\controller;

use app\api\model\BaseModel;
use app\api\model\RecycleOrderModel;
use app\api\model\RecyclePriceModel;
use app\api\model\RiderModel;
use app\api\model\UserModel;
use app\api\service\JsonService;
use app\common\controller\Api;
use think\Cache;
use wx\WxMessage;


/**
 * 接口
 */
class Recycle extends Api
{
    protected $noNeedLogin = ['price'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    //创建回收订单
    public function orderCreate()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'OrderValidate.create');
        if (true !== $result) {
            return JsonService::fail($result);
        }
        if (!is_array($params['category'])) {
            return JsonService::fail('分类参数错误');
        }
        $uid = $this->request->uid;
        $key = md5('user_order_' . $uid . time());
        if (Cache::has($key)) {
            return JsonService::fail('请勿重复提交订单');
        }
        Cache::set($key, 1, 2);
        $params['user_id'] = $uid;
        $order = RecycleOrderModel::createOrder($params);
        if (!$order) {
            return JsonService::fail(RecycleOrderModel::getErrorInfo());
        }
        //增加下单订阅消息提醒
        $user = UserModel::getUser($uid);
        $wx = new WxMessage();
        $data = $wx->createOrderMessage($user['openid'], $order);
        $wx->send_template_message($data);
        $order = RecycleOrderModel::getOrder($order->id);
        if ($order->role_id) { //如果被自动接单了，增加接单订阅消息提醒
            $rider = RiderModel::info($order->role_id);
            $data = $wx->takeOrderMessage($user['openid'], $order, $rider);
            $wx->send_template_message($data);
        }
        $data = [
            'id' => $order->id,
            'no' => $order->no,
        ];
        return JsonService::successful($data);
    }


    

    //订单列表
    public function orderList()
    {
        $params = $this->request->param();
        $uid = $this->request->uid;
        $list = RecycleOrderModel::lst($uid, $params);
        return JsonService::successful($list);
    }


}
